package com.apinji.common.plugin;

import com.apinji.common.plugin.fastjson.JSONUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * Created by Irvin on 2017/6/14
 */
public class Encode {

    public static String base64Encode(Object json) {
        try {
            return new BASE64Encoder().encode(toString(json).getBytes("GBK")).replace("\r\n", "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String base64Decode(String code){
        try {
            byte[] jsonByte = new BASE64Decoder().decodeBuffer(code);
            return new String(jsonByte, "GBK");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T base64DecodeToDomain(String code,Class<T> domainClass){
        try {
            byte[] jsonByte = new BASE64Decoder().decodeBuffer(code);
            return Optional.ofNullable(toDomain(new String(jsonByte, "GBK"),domainClass)).orElse(domainClass.newInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String md5Encode(String json){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(json.getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getSecret(){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update((uuid()+uuid()).getBytes());
            return new BigInteger(1, md.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String uuid(){
        return UUID.randomUUID().toString().replace("-","");
    }

    public static <T> T toDomain(String json,Class<T> domainClass){
        try{
            return JSONUtils.parseObject(json, domainClass);
        }catch(Exception ex){
            return null;
        }
    }

    public static <T> String toString(Object domain){
        try{
            return JSONUtils.parseJsonStr(domain);
        }catch(Exception ex){
            return null;
        }
    }

    public static String toSql(List list){
        if(list.size()==0)
            return "''";
        return list.toString().replace("[","").replace("]","");
    }
}
